import okex.futures_api as futures
import math

class trader_order():
    def __init__(self):
        userapi=[]
        for val in c.V3_API.values():
            userapi.append(val)
        self.user_api = futures.FutureAPI(userapi[0],userapi[1],userapi[2],True) # 用户api对象创建

    def open_close(self,type,match_price='0'):
        """
        :param type:  	1:开多2:开空3:平多4:平空
        match_price: 0 市价 1 限价
        :return:
        """
        if type =='开多':
            type ='1'
        elif type =='开空':
            type ='2'
        elif type =='平多':
            type='3'
        elif type =='平空':
            type ='4'

        if match_price =='limt':
            match_price = '1'



        size =1
        if c.open_long_short:
            leverage=float(c.open_long_short['leverage'])
        else: leverage = 10
        if c.now_price:
            price = str(c.now_price)
        else: price = str(0)

        if type == '1' or type == '2':
            if c.personal_masige: # 开单
                size = math.floor((float(c.personal_masige['equity'])/2 * float(c.now_price)/10 )* leverage) #  现在开一半多 一半空
        elif type =='3': # 平多单
            if c.open_long_short:
                size = c.open_long_short['long_avail_qty']
        elif type =='4':  #平空单
            if c.open_long_short:
                size = c.open_long_short['short_avail_qty']



        for i in range(5):
            try:
                info = self.user_api.take_order(client_oid=None,
                                         instrument_id=c.instrument_id,
                                         price=price, otype=type,
                                         size=str(size), match_price =match_price,
                                         leverage= leverage)
                return info

            except Exception as e:
                print(e)

if __name__ == '__main__':

    trader_order().open_close('1',0,'0')